<template>
	<view class="container bg-w">
		<view class="header uni-flex uni-row flex-between">
			<uni-nav-bar title="打卡考勤">
				<template slot='left'>
					<view class="flex width-100">
						<i class='iconfont iconfanhui' @click='goBack()'></i>
					</view>
				</template>
			</uni-nav-bar>
		</view>
		<view class="container_main">
			<view class="superior_select">
				<view class="superior_select_left">
					上级领导
				</view>
				<view class="superior_select_right">
					<uni-data-picker v-model="ccc" :localdata="superiorData" popup-title="请选择上级领导" @change="onchange"></uni-data-picker>
				</view>
			</view>
			<view>
				<uni-calendar
				:insert="true"
				:lunar="false"
				:headerBar="true"
				:selected="selected"
				:start_date="startDate"
				:end_date="endDate"
				@change="dateChange"
				@monthSwitch="monthChange"/>
			</view>
			<view class="clock_records" v-for="(item,index) in attenList" :key="index">
				<view v-if="item.clockStatus == 0">
					<p class="time_add">
						<span class="clock-address"><uni-icons type="location" size="14" color="blue"></uni-icons>{{item.address || "--"}}</span>
						<text class="clock_time">{{item.createTime || "--"}}</text>
					</p>
				</view>
				<view v-else-if="item.clockStatus == 1">
					<p class="reson_time_list">
						<span class="clock-address"><text>类别：</text>请假</span>
						<text class="clock_time"><text>开始时间：</text>{{item.beginTime}}</text>
					</p>
					<p class="reson_time_list">
						<span class="clock-address"><text>事由：</text>{{item.reason}}</span>
						<text class="clock_time"><text>结束时间：</text>{{item.endTime}}</text>
					</p>
				</view>
				<view v-else-if="item.clockStatus == 2">
					<p><span class="clock-address"><text>类别：</text>补卡</span></p>
					<p class="reson_time_list">
						<span class="clock-address"><text>事由：</text>{{item.reason}}</span>
						<text class="clock_time">{{item.createTime || "--"}}</text>
					</p>
				</view>
			</view>
		</view>
		<view class="atten_btns">
			<button type="default" class="atten_btn" :class="leaveStatus?!clockStatus?'atten_btn_max':'':''" v-if="leaveStatus" @click="clockOpen(1)">请假</button>
			<button type="warn" class="atten_btn" :class="replaceStatus?'atten_btn_max':''" v-if="replaceStatus" @click="clockOpen(2)">补卡</button>
			<button type="primary" class="atten_btn" v-if="clockStatus" @click="clockOpen(0)">打卡</button>
		</view>
		
		<uni-popup ref="popup" type="dialog">
			<view class="popup-content" v-if="popStatus == 0">
				<view class="pop_title">打卡提示</view>
				<form @submit="formSubmit" @reset="formClose">
					<view class="uni-form-item uni-column">
						<view class="pop_form_label" style="display: none;">
							<picker @change="bindPickerChange" :value="index" :range="array" range-key="name">
								<input type="text" @click="activeNo" :value="clickForm.subProjectId" placeholder="请选择负责子项目">
							</picker>
						</view>
					</view>
					<view class="uni-form-item uni-column">
						<view class="pop_form_label">
							<input type="text" disabled name="createTime" v-model="clickForm.createTime">
							<!-- <text class="pop_addresssinfo">{{clickForm.createTime}}</text> -->
						</view>
					</view>
					<view class="uni-form-item uni-column">
						<view class="pop_form_label">
							<input type="text" disabled name="address" placeholder="请选择地址信息" @click="getLocationMsg" v-model="clickForm.address">
							<!-- <text class="pop_addresssinfo" @click="getLocationMsg">{{clickForm.address}}</text> -->
						</view>
					</view>
					<view class="uni-btn-v">
						<button type="default" size="mini" form-type="reset">取消</button>
						<button type="primary" size="mini" form-type="submit">打卡</button>
					</view>
				</form>
			</view>
			<view class="popup-content" v-if="popStatus == 1">
				<view class="pop_title">请假事由</view>
				<form @submit="leaveFormSubmit">
					<view class="uni-form-item uni-column">
						<view class="pop_form_area">
							<text class="pop_form_title">开始时间：</text>
							<uni-datetime-picker :value="clickForm.beginTime" name="beginTime" start="2011-1-1" end="2035-12-31" @change="leaveStartChange"></uni-datetime-picker>
						</view>
						<view class="pop_form_area">
							<text class="pop_form_title">结束时间：</text>
							<uni-datetime-picker :value="clickForm.endTime" name="endTime" start="2011-1-1" end="2035-12-31" @change="leaveEndChange"></uni-datetime-picker>
						</view>
					</view>
					<view class="uni-form-item uni-column">
						<view class="pop_form_area">
							<textarea v-model="clickForm.reason" name="reason" placeholder="请输入请假事由" auto-height/>
						</view>
					</view>
					<view class="uni-btn-v">
						<button type="primary" size="mini" form-type="submit">提交</button>
					</view>
				</form>
			</view>
			<view class="popup-content" v-if="popStatus == 2">
				<view class="pop_title">补卡原因</view>
				<form>
					<view class="uni-form-item uni-column">
						<view class="pop_form_area">
							<text class="pop_form_title">补卡时间：</text>
							<uni-datetime-picker :value="clickForm.replaceTime" start="2011-1-1" end="2035-12-31" @change="replacedateChange"></uni-datetime-picker>
						</view>
						<view class="pop_form_area">
							<textarea v-model="clickForm.reason" placeholder="请输入补卡原因" auto-height/>
						</view>
					</view>
					<view class="uni-btn-v">
						<button type="primary" size="mini" @click="replaceFormSubmit">提交</button>
					</view>
				</form>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import	{ clickPunch, getSuperior, getClickList, getMonthClickDays } from "@/common/api/attenApi.js"
export default {
	data() {
		return {
			startDate: "2021-1-1",
			endDate: "2021-12-31",
			selected: [],
			selectDate: "",
			time:"",
			dateStatus: "",
			leaveStatus: true,
			replaceStatus: false,
			clockStatus: true,
			popStatus: null,
			attenList: [],
			auditUserId: "",
			ccc: "",
			superiorData: [],
			array: [{name:'中国'},{name: '美国'}, {name:'巴西'}, {name:'日本'}],
			index: 0,
			clickForm:{
				userId: "", // 员工ID
				clockStatus: "", //打卡状态
				reason: "",
				latitude: "", //纬度
				longitude: "", //经度
				subProjectId: "", //子项目id
				createTime: "", //打卡时间
				address: "" ,//地点
				beginTime: "",  // 请假开始时间
				endTime: "",  // 请假结束时间
				replaceTime: "",  // 补卡时间
			}
		}
	},
	mounted(){
		this.clickForm.createTime = this.getTime()
		this.auditUserId = uni.getStorage({
			key: 'auditUserId',
			success: function (res) {
				return res.data
			}
		});
		this.getSuperiored()
		this.getClickLists()
		this.monthChange()
	},
	methods: {
		getSuperiored: function() {
			let _this = this
			getSuperior().then(res=>{
				_this.superiorData = res.data
			})
		},
		/**
		 * 查询打卡记录列表
		 * @method getClickLists
		 * @param {Object} time 选择的时间
		 */
		getClickLists: function(time) {
			let _this = this
			let date = time ? time : this.clickForm.createTime.split(" ")[0]
			getClickList({date}).then(res=>{
				_this.attenList = res.data
			})
		},
		/**
		 * 日期月份改变
		 * @method dateChange & monthChange
		 * @param {Object} dateobj 选择后返回的值
		 * @param {Object} monthobj 选择后返回的值
		 */
		stringToDate:function(DateStr){
			let timestamp = new Date(this.getLocalDate()).getTime();
		    let myDate = new Date(DateStr).getTime();
		    if (myDate < timestamp) {
		        return 2
		    }else if(myDate > timestamp) {
				return 1
			}else{
				return 0
			}
		},
		dateChange: function(dateobj) {
			this.selectDate = dateobj.fulldate
			this.clickForm.replaceTime = this.initTime(dateobj.fulldate)
			this.clickForm.beginTime = this.initTime(dateobj.fulldate)
			this.clickForm.endTime = this.initTime(dateobj.fulldate)
			this.clickForm.createTime = this.initTime(dateobj.fulldate)
			if(this.stringToDate(dateobj.fulldate) === 1){
				this.dateStatus = 1
			}else if(this.stringToDate(dateobj.fulldate) === 2){
				this.dateStatus = 2
			}else{
				this.dateStatus = 0
			}
			// 控制按钮状态
			switch(this.dateStatus){
				case 1:
					this.leaveStatus = true;
					this.replaceStatus = false;
					this.clockStatus = false
					break;
				case 2:
					this.leaveStatus = false;
					this.replaceStatus = true;
					this.clockStatus = false
					break;
				default:
					this.leaveStatus = true;
					this.replaceStatus = false;
					this.clockStatus = true
			}
			this.clickForm.reason = ""
			this.getClickLists(dateobj.fulldate)
		},
		monthChange: function(monthobj) {
			let _this = this
			let month = ""
			if(monthobj){
				let monthType = (monthobj.month+'').length < 2 ? '0'+ monthobj.month : monthobj.month
				month = monthobj.year + "-" + monthType
			}else{
				month = this.getMonth()
			}
			// 获取当前选择月打卡日期列表
			getMonthClickDays({date: month}).then(res=>{
				let dateList = res.data
				let obj = {};
				if(dateList && dateList.length>0){
					dateList.forEach(item=>{
						_this.selected.push({ date: item })
					})
					_this.selected = _this.selected.reduce(function(item, next) {
						obj[next.date] ? '' : obj[next.date] = true && item.push(next);
						return item;
					}, []);
				}
			})
		},
		/**
		 * 上级领导选择改变
		 * @method onchange
		 * @param {Array} value 选择后返回的value值
		 */
		onchange: function(value) {
			this.auditUserId = value
			try{
				uni.setStorageSync('auditUserId', value[1]);
			}catch(err){
				//TODO handle the exception
			};
		},
		leaveStartChange: function(time) {
			this.clickForm.beginTime = time;
		},
		leaveEndChange: function(time) {
			this.clickForm.endTime = time;
		},
		replacedateChange: function(time) {	
			this.clickForm.createTime = time;
		},
		clockOpen: function(status){
			this.popStatus = status
			// 通过组件定义的ref调用uni-popup方法
			this.$refs.popup.open()
		},
		formSubmit: function(e) {
			let _this = this
			let params = e.detail.value
			if(!params.address){
				uni.showToast({ icon:'none', title:'请获取位置信息', duration: 1500 });
				return;
			}
			let data = {...this.clickForm, ...params};
			// data["createTime"] = this.selectDate || this.getTime();
			data["clockStatus"] = this.popStatus;
			if(this.auditUserId){
				data["auditUserId"] = this.auditUserId[1];
			}else{
				uni.showToast({
					title: '请选择上级领导',
					icon:'none',//不要图标
					duration: 1500//1后消失
				});
				return;
			}
			clickPunch(data).then(res=>{
				if(res.code === "20000"){
					uni.showToast({ title: '打卡成功', duration: 2000 });
					_this.formClose()
					_this.monthChange()
					_this.getClickLists()
				}
			})
		},
		leaveFormSubmit:function() {
			let _this = this;
			let data = {...this.clickForm};
			if(!data.beginTime || !data.endTime){
				uni.showToast({ icon:'none', title:'请获取开始和结束时间', duration: 1500 });
				return;
			}
			if(!data.reason){
				uni.showToast({ icon:'none', title:'请填写请假理由', duration: 1500 });
				return;
			}
			data["clockStatus"] = this.popStatus;
			data["createTime"] = this.selectDate ? this.selectDate + " 12:00:00" : this.getTime();
			if(this.auditUserId){
				data["auditUserId"] = this.auditUserId[1];
			}else{
				uni.showToast({
					title: '请选择上级领导',
					icon:'none',//不要图标
					duration: 1500//1后消失
				});
				return;
			}
			clickPunch(data).then(res=>{
				if(res.code === "20000"){
					uni.showToast({
					    title: '提交成功',
					    duration: 2000
					});
					_this.formClose()
					_this.monthChange()
					_this.getClickLists()
					_this.clickForm.reason = ""
				}
			})
		},
		replaceFormSubmit:function() {
			let _this = this;
			let data = {...this.clickForm};
			if(!data.createTime){
				uni.showToast({ icon:'none', title:'请选择补卡时间', duration: 1500 });
				return;
			}
			if(!data.reason){
				uni.showToast({ icon:'none', title:'请填写补卡理由', duration: 1500 });
				return;
			}
			data["clockStatus"] = this.popStatus;
			if(this.auditUserId){
				data["auditUserId"] = this.auditUserId[1];
			}else{
				uni.showToast({
					title: '请选择上级领导',
					icon:'none',//不要图标
					duration: 1500//1后消失
				});
				return;
			}
			clickPunch(data).then(res=>{
				if(res.code === "20000"){
					uni.showToast({
					    title: '提交成功',
					    duration: 2000
					});
					_this.formClose()
					_this.monthChange()
					_this.getClickLists()
					_this.clickForm.reason = ""
				}
			})
		},
		formClose: function(){
			this.$refs.popup.close()
		},
		bindPickerChange: function(e) {
			this.projectName = this.array[e.detail.value].name
		},
		getTime:function(){
			let date = new Date(),
			year = date.getFullYear(),
			month = date.getMonth() + 1,
			day = date.getDate(),
			hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
			minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
			second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
			month >= 1 && month <= 9 ? (month = "0" + month) : "";
			day >= 0 && day <= 9 ? (day = "0" + day) : "";
			let timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
			return timer;
		},
		getMonth:function(){
			let date = new Date(),
				year = date.getFullYear(),
				month = date.getMonth() + 1;
			month >= 1 && month <= 9 ? (month = "0" + month) : "";
			let timer = year + '-' + month
			return timer;
		},
		initTime: function(time){
			return time + " 00:00:00"
		},
		getLocalDate:function(){
			let nowDate = new Date();
			let year = nowDate.getFullYear();
			let month = nowDate.getMonth() + 1 < 10 
				? "0" + (nowDate.getMonth() + 1)
				: nowDate.getMonth() + 1;
			let day = nowDate.getDate() < 10 
				? "0" + nowDate.getDate() 
				: nowDate.getDate();
			return year + "-" + month + "-" + day;
		},
		activeNo:function(){
			setTimeout(function(){
				uni.hideKeyboard();//隐藏软键盘
			},50);
		},
		/**
		 * 获取定位信息
		 * @method getLocationMsg
		 * @param {Array} value 选择后返回的value值
		 */
		getLocationMsg:function(){
			let _this = this
			uni.chooseLocation({
			    success: function (res) {
					_this.clickForm.address = res.address
					_this.clickForm.latitude = res.latitude
					_this.clickForm.longitude = res.longitude
			    }
			});
		}
	}
}
</script>

<style lang="less">
	.container_main{
		position: relative;
		top: 70px;
		overflow-y: scroll;
		height: calc(100% - 116px);
		background-color: #eee;
	}
	.superior_select{
		position: relative;
		display: flex;
		justify-content: space-between;
		margin: 5px 5px;
		padding: 0 10px;
		height: 30px;
		background: #fff;
		line-height: 30px;
	}
	.clock_records{
		margin-top: 2px;
		padding: 5px 20px;
		font-size: 16px;
		background-color: #fff;
		border-top: 1px solid #eee;
		&:hover{
			background-color: #ccc
		}
		.reson_time_list{
			display: flex;
			height: 30px;
			line-height: 30px;
			justify-content: space-between;
			.clock-address{
				display: inline-block;
				width: 44%;
				overflow: hidden;
				text-overflow:ellipsis; white-space: nowrap;
			}
		}
		.time_add{
			display: flex;
			height: 50px;
			line-height: 50px;
			justify-content: space-between;
			.clock-address{
				display: inline-block;
				width: 60%;
				overflow: hidden;
				text-overflow:ellipsis; 
				white-space: nowrap;
			}
		}
		.clock_time{
			position: relative;
			overflow: hidden;
			text-overflow:ellipsis; 
			white-space: nowrap;
		}
	}
	.atten_btns{
		display: flex;
		position: fixed;
		width: 100%;
		bottom: 0;
		.atten_btn{
			margin: 0;
			width: 50%;
			border-radius: 0;
		}
		uni-button:after{
			border-radius: 0;
		}
		.atten_btn_max{
			width: 100%;
		}
	}
	.popup-content{
		position: relative;
		width: 300px;
		border-radius: 10px;
		padding: 10px;
		background-color: #fff;
		overflow: hidden;
		.pop_title{
			margin-bottom: 20px;
		}
		.pop_form_area {
			display: flex;
			width: 90%;
			margin: 10px auto;
			background-color: #fff;
			border: 1px solid #09AAE9;
			border-radius: 5px;
			uni-datetime-picker{
				width: 100%;
				line-height: 38px;
			}
		}
		.pop_form_title{
			height: 38px;
			line-height: 38px;
			text-indent: 5px;
		}
		.pop_form_label{
			width: 90%;
			height: 38px;
			line-height: 38px;
			margin: 10px auto;
			background-color: #fff;
			border: 1px solid #09AAE9;
			border-radius: 5px;
			uni-input {
				height: 38px;
				line-height: 38px;
				text-align: center;
			}
			.pop_addresssinfo {
				display: block;
				width: 100%;
				height: 100%;
				text-align: center;
				overflow: hidden;
			}
		}
		.uni-btn-v{
			width: 95%;
			margin-top: 10px;
			uni-button{
				float: right;
				margin-left: 10px;
			}
		}
	}
</style>
